/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package data_access;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Calendar;

/**
 * 
 * @author Anh
 */
public class DataAccess {

	public Connection cn = null;

	public DataAccess() throws Exception {
		String hostName = "127.0.0.1";
		String port = "3306";

		String dbName = "classification";
		String userName = "root";
		String password = "";

		Class.forName("com.mysql.jdbc.Driver");
		String connectionURL = "jdbc:mysql://" + hostName + ":" + port + "/" + dbName;

		cn = DriverManager.getConnection(connectionURL, userName, password);
	}

	public ResultSet getData(String tbName) throws SQLException {
		ResultSet kq = null;
		Statement st = cn.createStatement();
		String sqlQuery = "select * from " + tbName;
		kq = st.executeQuery(sqlQuery);
		return kq;
	}

	public void deleteData(ResultObj obj) throws SQLException {
		String query = "delete from result where id = (?)";

		PreparedStatement preparedStmt = cn.prepareStatement(query);
		preparedStmt.setInt(1, obj.getId());
		preparedStmt.execute();
	}

	public void insertResult(ResultObj obj) throws SQLException {
		Calendar calendar = Calendar.getInstance();
		Timestamp datetime = new Timestamp(calendar.getTimeInMillis());

		String query = " insert into result (dataname, testingsize, classnumber, accoao, timeoao, accddag, timeddag, accadag, timeadag, date)"
				+ " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

		PreparedStatement preparedStmt = cn.prepareStatement(query);
		preparedStmt.setString(1, obj.getDataName());
		preparedStmt.setInt(2, obj.getTestingSize());
		preparedStmt.setInt(3, obj.getClassNumber());
		preparedStmt.setDouble(4, obj.getAccOAO());
		preparedStmt.setInt(5, obj.getTimeOAO());
		preparedStmt.setDouble(6, obj.getAccDDAG());
		preparedStmt.setInt(7, obj.getTimeDDAG());
		preparedStmt.setDouble(8, obj.getAccADAG());
		preparedStmt.setInt(9, obj.getTimeADAG());
		preparedStmt.setTimestamp(10, datetime);

		preparedStmt.execute();
	}

	public void closeConnect() throws Exception {
		if (cn != null) {
			cn.close();
		}
	}
}
